package com.blank.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.blank.model.Company;
import com.blank.site.Cn716Site;
import com.blank.site.Huangye88Site;
import com.blank.site.PageSite;
import com.blank.site.SunQiSite;
import com.blank.site.T51SoleSite;

public class Main {
	
	public void getDatas(){
		this.clean();
		new SunQiSite().run();
		new T51SoleSite().run(); 	
		new Huangye88Site().run();
		new PageSite().run();
		new Cn716Site().run();
		System.out.println("抓取数据完成");
	}
	
	public void ExportExcel(){
		ExportExcel<Company> exportExcel = new ExportExcel<Company>();
		String[] headers2 = { "id", "手机", "公司名", "内容","邮箱", "地址",
	            "网站", "来源" ,"封面图片" };
	      List<Company> dataset = new ArrayList<Company>();
	       try {
	    	   InputStream is;
				is = Resources.getResourceAsStream("mybatis-config.xml");
				// 建立Session工厂
				SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
				// 获取Session
				SqlSession session = factory.openSession();
				dataset = session.selectList(Company.class.getName()+".list");
				FileOutputStream fos = new FileOutputStream("导出.xls");
			exportExcel.exportExcel(headers2,dataset,fos);
			fos.close();
			session.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	       File file =new File("导出.xls");
	       System.out.println("导出成功,路径为:"+file.getAbsolutePath());
		
	}
	
	public void clean(){
		 InputStream is;
			try {
				is = Resources.getResourceAsStream("mybatis-config.xml");
				// 建立Session工厂
				SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
				// 获取Session
				SqlSession session = factory.openSession();
				session.selectOne(Company.class.getName()+".clean");
				session.commit();
				session.close();
				System.out.println("清空完成");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			
	}
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		Main main = new Main();
		
		while(true){
			System.out.println("1.抓取数据\n2.导出excel\n3.清空数据库\n4.退出");
			String choice =sc.next();
			if(choice.equals("1"))
				main.getDatas();
			else if(choice.equals("2"))
				main.ExportExcel();
			else if(choice.equals("3"))
				main.clean();
			else if(choice.equals("4"))
				System.exit(0);;
			
		}
	}

}
